import {Component, OnInit} from '@angular/core';
import {Http} from '@angular/http';
import {FormGroup, FormBuilder, Validators, NgForm} from '@angular/forms';
import {Router, ActivatedRoute} from '@angular/router';

@Component({
  selector: 'app-book-edit',
  templateUrl: './book-edit.component.html',
  styleUrls: ['./book-edit.component.css']
})
export class BookEditComponent implements OnInit {

  id: String;
  typeList: Array<Object>;
  book: any;
  responseErr: String = '';
  state: Boolean = false;

  getTypeList() {
    return new Promise((resolve, reject) => {
      this.http.post('booktype/getBookTypeList', null)
        .map(response => response.json())
        .subscribe(data => {
          if (data.code === 0) {
            this.typeList = data.data.content;
            resolve()
          } else {
            reject(data.msg)
          }
        })
    })
  }

  getDetail() {
    this.http.post(`book/detail?id=${this.id}`, null)
      .map(res => res.json())
      .subscribe(data => {
        if (data.code === 0) {
          this.book = data.data;
          this.state = this.book['state'] === 'checkIn';
        } else {
          alert(data.msg)
        }
      });
  }

  submit(form: NgForm) {
    this.responseErr = '';
    if (form.hasError('required', ['bookname'])) {
      this.responseErr = '未填写书名'
    } else if (form.hasError('required', ['author'])) {
      this.responseErr = '未填写作者'
    } else if (form.hasError('required', ['isbn'])) {
      this.responseErr = '未填写ISBN号'
    } else if (form.hasError('required', ['remark'])) {
      this.responseErr = '未填写简介'
    }
    if (form.valid) {
      this.book['state'] = this.state ? 'checkIn' : 'fail';
      this.http.post('book/save', Object.assign(this.book, form.value))
        .map(res => res.json())
        .subscribe(data => {
          if (data.code === 0) {
            this.router.navigate(['book-list'])
          } else {
            this.responseErr = data.msg
          }
        });
    }
    // console.log(form)
  }

  constructor(private http: Http, private router: Router, private route: ActivatedRoute) {
    this.book = {}
  }

  ngOnInit() {

    this.id = this.route.snapshot.paramMap.get('id');
    this.getTypeList().then(() => {
      this.id !== 'add' && this.getDetail()
    })

  }

}
